package web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import dto.OderDto;
import dto.OderItemDto;
import entity.Admin;
import entity.Oder;
import entity.Oder_Item;
import entity.PayInfo;
import entity.Product;
import entity.Traveler;
import entity.User;
import enums.travelenums;
import service.Cart_service;
import service.Oder_service;
import service.Product_service;

@Controller
public class Oder_controller {
	private static final Logger log=LoggerFactory.getLogger(Oder_controller.class);
	
	@Autowired
	private Oder_service oder_service;
	
	@Autowired
	private Product_service product_service;
	
	@Autowired
	private Cart_service cart_service;
	
	@RequestMapping(value="user/topay",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject SaveOder(String str,HttpServletRequest request) throws Exception{
		
		String[] result_id = request.getParameterValues("product_id");
		String[] result_qua = request.getParameterValues("quantity");
		String[] result_date=request.getParameterValues("target_date");
		String pay_price=request.getParameter("pay_price");
		log.info("支付价格"+pay_price);
		if(result_id!=null&&result_qua!=null&&pay_price!=null&&result_date!=null)
		{
			JSONObject jsonObject = JSONObject.parseObject(str); 
			String conPersonname=jsonObject.getString("conPersonname");  
			String conPhone=jsonObject.getString("conPhone");
			String conEmail=jsonObject.getString("conEmail");
			String tra1Personname=jsonObject.getString("tra1Personname");
			String tra1Idcard=jsonObject.getString("tra1Idcard");
			String tra1Country=jsonObject.getString("tra1Country");
			String tra1Phone=jsonObject.getString("tra1Phone");
			String tra2Personname=jsonObject.getString("tra2Personname");
			String tra2Idcard=jsonObject.getString("tra2Idcard");
			String tra2Country=jsonObject.getString("tra2Country");
			String tra2Phone=jsonObject.getString("tra2Phone");
			System.out.println(jsonObject);
			
			User user=(User)request.getSession().getAttribute("user");
			SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String Time =sd.format(new Date());
			
			SimpleDateFormat sd_ss=new SimpleDateFormat("ss");		
			Integer oderId=Integer.parseInt( sd_ss.format(new Date())+String.valueOf(Math.round(Math.random()*100))+user.getId().toString()+String.valueOf(Math.round(Math.random()*100)) );
			log.info("订单号"+oderId);	 //先是字符串连接，在变成数字,生成随机订单号
			double payPrice=Double.parseDouble(pay_price);
			
			Oder oder=new Oder(oderId,user.getId(),payPrice,travelenums.ALIPAY.getState(),Time,Time);	//101-支付宝支付
			Traveler traveler=new Traveler(user.getId(),oderId,conPersonname,conPhone,conEmail,tra1Personname,tra1Idcard,tra1Country,tra1Phone,tra2Personname,tra2Idcard,tra2Country,tra2Phone,Time,Time);
			oder_service.saveOderAndTraveler(oder, traveler);
			
			int[] product_id=new int[result_id.length];
			int[] quantity=new int[result_qua.length];
			String[] target_date=new String[result_date.length];
			for(int i=0;i<result_id.length;i++){
				product_id[i]=Integer.parseInt(result_id[i]);
				quantity[i]=Integer.parseInt(result_qua[i]);
				target_date[i]=result_date[i];
				log.info("商品id"+product_id[i]);
				log.info("数量"+quantity[i]);
				log.info("预定日期"+target_date[i]);
				Product pro=product_service.getproByid(product_id[i]);
				double proPrice=pro.getProPrice();
				double productTotalprice=quantity[i]*proPrice;
				Oder_Item oder_Item=new Oder_Item(user.getId(),oderId,product_id[i],"<"+pro.getProName()+">"+pro.getProDescription(),pro.getMainImage(),proPrice,quantity[i],target_date[i],productTotalprice,Time,Time);
				oder_service.save_oderItem(oder_Item);
				cart_service.remove_FromCart(product_id[i], user.getId());
			}			
			JSONObject jsObject=oder_service.getQrCodeAndOder(user.getId(), oderId);
			return jsObject;
	  }else{ 
				JSONObject object=new JSONObject();
				object.put("erro", "erro");
				log.info("获取订单信息失败");
				return object; 
			}
	}
	
			/*支付验签*/
	@RequestMapping(value="alipay_callback.do")
	@ResponseBody
	public Object alipay_callback(HttpServletRequest request){
		Map<String,String> Params=new HashMap<>();		
		 Map requestParams =request.getParameterMap();
		for(Iterator iter=requestParams.keySet().iterator(); iter.hasNext();){
			String name=(String)iter.next();
			String[] values=(String[])requestParams.get(name);
			String valuestr="";
			for(int i=0;i<values.length;i++){
				valuestr = (i==values.length-1)?valuestr + values[i]:valuestr + values[i]+",";
			}
			Params.put(name, valuestr);
		}
		log.info("支付宝回调:sign{},trade_status{},参数{}",Params.get("sign"),Params.get("trade_status"),Params.toString());
		Params.remove("sign_type");
		try {
			boolean alipayRSACheckedV2=AlipaySignature.rsaCheckV2(Params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
			if(!alipayRSACheckedV2){
				log.info("非法请求，验证不通过");
				return "非法请求，验证不通过";				
			}	
		} catch (AlipayApiException e) {
			log.info("支付宝回调异常",e);
		}
		
		String result=oder_service.alipaycallback(Params);
		if(result=="succ"){
			return travelenums.AlipayCallBack.RESPONSE_SUCCESS;
		}else{
			return travelenums.AlipayCallBack.RESPONSE_FAILED;
		}
		
	}
	/*支付宝支付前台轮询查询订单状态*/
	
	@RequestMapping(value="user/QueryOderStatus",method=RequestMethod.POST)
	@ResponseBody
	public String QueryOderStatus(Integer oderId){
		boolean boo=oder_service.QueryOderStatus(oderId);
		log.info("正在检查订单状态....");
		if(boo){
			return "true";
		}else {
			return "false";
		}
	}			
			/*查询所有订单（无法用status）*/
	@RequestMapping(value="user/usercenter/queryall")
	@ResponseBody							
	public JSONArray QueryAll(@RequestParam(value="page",required=true,defaultValue="1")Integer page,
								HttpSession session){
			User user=(User)session.getAttribute("user");

			Page<Oder> pa=PageHelper.startPage(page, 4);
			List<Oder> oderlist=oder_service.oder_list(user.getId());
			PageInfo<Oder> p=new PageInfo<Oder>(pa);
			JSONArray jsonarr=new JSONArray();
			for (Oder oder : oderlist) {
				Integer status=oder.getStatus();		//订单状态
				Integer oderId=oder.getOderId();
				Traveler traveler=oder_service.get_Traveler(user.getId(), oderId);
				List<Oder_Item> oderItem_list=oder_service.get_oderItemByOderId(oderId);
				for (Oder_Item oder_Item : oderItem_list) {
					JSONObject jo=new JSONObject();
					jo.put("creat_time", oder_Item.getCreateTime());
					jo.put("oder_id", oder_Item.getOderId());
					jo.put("productId", oder_Item.getProductId());
					jo.put("pro_pic", oder_Item.getProductPic());
					jo.put("name", oder_Item.getProductName());
					jo.put("target_date",oder_Item.getTargetDate());
					jo.put("quantity", oder_Item.getQuantity());
					jo.put("total_price", oder_Item.getProductTotalprice());
					jo.put("status", travelenums.stateOf(status).getInfo());//枚举类与数据库对应
					jo.put("traveler1", traveler.getTra1Personname());
					jo.put("traveler2", traveler.getTra2Personname());
					jo.put("nextpage", p.getNextPage());
					jo.put("prepage", p.getPrePage());		/*分页信息*/
					jo.put("pages", p.getPages());
					jo.put("pagenum", p.getPageNum());
					jsonarr.add(jo);
				}
			}
		return jsonarr;
	}

	
	/*复用的方法，通过status查询订单*/	
	@ResponseBody
	@RequestMapping(value="user/usercenter/queryoder")
	public JSONArray QueryOderByStatus(@RequestParam(value="page",required=true,defaultValue="1")Integer page,
										HttpSession session,Integer status){
		
		User user=(User)session.getAttribute("user");

		Page<Oder_Item> pa=PageHelper.startPage(page, 4);
		List<Oder_Item> oderItem_list=oder_service.oder_listBystatus(user.getId(), status);
		PageInfo<Oder_Item> p=new PageInfo<Oder_Item>(pa);
		JSONArray jsonarr=new JSONArray();
			for (Oder_Item oder_Item : oderItem_list) {
				Integer oderId=oder_Item.getOderId();
				Traveler traveler=oder_service.get_Traveler(user.getId(), oderId);
				JSONObject jo=new JSONObject();
				jo.put("creat_time", oder_Item.getCreateTime());
				jo.put("oder_id", oder_Item.getOderId());
				jo.put("productId", oder_Item.getProductId());
				jo.put("pro_pic", oder_Item.getProductPic());
				jo.put("name", oder_Item.getProductName());
				jo.put("target_date",oder_Item.getTargetDate());
				jo.put("quantity", oder_Item.getQuantity());
				jo.put("total_price", oder_Item.getProductTotalprice());
				jo.put("status", travelenums.stateOf(status).getInfo());//枚举类与数据库对应
				jo.put("traveler1", traveler.getTra1Personname());
				jo.put("traveler2", traveler.getTra2Personname());
				jo.put("nextpage", p.getNextPage());
				jo.put("prepage", p.getPrePage());		/*分页信息*/
				jo.put("pages", p.getPages());
				jo.put("pagenum", p.getPageNum());
				jsonarr.add(jo);
			}	
			return jsonarr;	
	}
	
	@RequestMapping(value="user/repay",method=RequestMethod.POST)
	@ResponseBody
	public String repay(HttpSession session,Integer oderId){
		User user=(User)session.getAttribute("user");
		if(user!=null){
			PayInfo payinfo =oder_service.getPayInfoByOderId(user.getId(), oderId);
			return payinfo.getPayUrl();
		}
		return travelenums.NOLOGIN.getInfo();
	}
	
	@RequestMapping(value="user/cancel/oder",method=RequestMethod.POST)
	@ResponseBody
	public String cancelOder(HttpSession session,Integer oderId){
		User user=(User)session.getAttribute("user");
		if(user!=null){
			Oder oder=oder_service.get_oderByoderId(oderId);
			if(oder!=null){
				oder.setStatus(travelenums.CANCEL.getState());
				try {
					boolean boo=oder_service.update_oder(oder);
					if(boo){
						return travelenums.SUCCESS.getInfo();
					}
					return travelenums.ERRO.getInfo();
				} catch (Exception e) {
					log.error("取消订单失败",e);
				}
			}
			return travelenums.ERRO.getInfo();
		}
		return travelenums.NOLOGIN.getInfo();
	}
	
	
		/*后台*/
	
		@RequestMapping(value="backoderlist",method=RequestMethod.POST)
		public String BackOderList(@RequestParam(value="page",defaultValue="1",required=true)Integer page,
									Model model){
			Page<OderDto> pa=PageHelper.startPage(page, 10);
			List<OderDto> list=oder_service.oderDtoList();
			PageInfo<OderDto> pageInfo=new PageInfo<OderDto>(pa);
			model.addAttribute("page", pageInfo);
			model.addAttribute("OderDtolist", list);
			return "back/oder";
		}
		@RequestMapping(value="backoderdetail",method=RequestMethod.POST)
		public String Backoderdetail(@RequestParam("id")Integer oderId,Model model){
			OderItemDto  oderItemDto =oder_service.oderItemDtoByOderId(oderId);
			model.addAttribute("oderItemDto", oderItemDto);
			return "back/oderdetail";
		}
	
		/*这里的id指（真正的id（porid，oderid），可以是别的obj，string）前段函数复用的结果*/
		@RequestMapping(value="backsearchoder",method=RequestMethod.POST)
		public String BackSearchOder(@RequestParam(value="page",defaultValue="1",required=true)Integer page,
									@RequestParam("id")Integer oderId,Model model){
			Page<OderDto> pa=PageHelper.startPage(page, 10);
			List<OderDto> list=oder_service.getOderDtoByOderId(oderId);
			PageInfo<OderDto> pageInfo=new PageInfo<OderDto>(pa);
			model.addAttribute("page", pageInfo);
			model.addAttribute("OderDtolist", list);
			return "back/oder";
		}
		
		@RequestMapping(value="delete/oder")
		@ResponseBody
		public String deleteOder(Integer oderId,HttpSession session){
			Admin admin=(Admin)session.getAttribute("admin");
			if(admin!=null){
				boolean boo=oder_service.remove_oder(oderId);
				if(boo){
					return travelenums.SUCCESS.getInfo();
				}
				return travelenums.ERRO.getInfo();
			}
			return travelenums.NOLOGIN.getInfo();
		}
}
